package com.scs.application.modules.dept.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.modules.dept.entity.BudgetMatr;
import com.scs.application.modules.dept.mapper.BudgetMatrMapper;
import com.scs.application.modules.dept.service.BudgetMatrService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 科室预算明细-耗材表 服务实现类
 * </p>
 */
@Service
public class BudgetMatrServiceImpl extends BaseServiceImpl<BudgetMatrMapper, BudgetMatr> implements BudgetMatrService {

    /**
     * @Description：批量保存限制耗材
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatchItemMatr(List<BudgetMatr> entityList) {

        //已存在的设置id
        List<String> matrIds = entityList.stream().map(BudgetMatr::getMatrId).collect(Collectors.toList());
        List<BudgetMatr> budgetMatrDbList = this.list(Wrappers.<BudgetMatr>query()
                .eq("budget_item_id",entityList.get(0).getBudgetItemId())
                .in("matr_id",matrIds)
        );
        if (budgetMatrDbList != null && budgetMatrDbList.size() > 0) {
            Map<String,BudgetMatr> matrIdMap=new HashMap<String,BudgetMatr>();
            budgetMatrDbList.stream().forEach(budgetMatrTmp -> matrIdMap.put(budgetMatrTmp.getMatrId(),budgetMatrTmp));
            String matrId;
            for(int i=0;i < entityList.size() ;i++){
                matrId = entityList.get(i).getMatrId();
                if (matrIdMap.containsKey(matrId)) entityList.get(i).setId(matrIdMap.get(matrId).getId());
            }
        }

        this.saveOrUpdateBatch(entityList);
    }

}
